package com.zdb.n1.controller;

import com.zdb.n1.entity.ExerciseRecord;
import com.zdb.n1.entity.User;
import com.zdb.n1.payload.response.MessageResponse;
import com.zdb.n1.repository.ExerciseRecordRepository;
import com.zdb.n1.repository.UserRepository;
import com.zdb.n1.service.ExerciseRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/api/admin/exercise-records")
@PreAuthorize("hasRole('ADMIN')")
public class AdminExerciseController {

    @Autowired
    private ExerciseRecordRepository exerciseRecordRepository;
    
    @Autowired
    private UserRepository userRepository;
    
    @Autowired
    private ExerciseRecordService exerciseRecordService;
    
    /**
     * 获取指定用户的所有运动记录
     */
    @GetMapping("/user/{userId}")
    public ResponseEntity<List<ExerciseRecord>> getUserExerciseRecords(@PathVariable Long userId) {
        Optional<User> userOpt = userRepository.findById(userId);
        if (userOpt.isEmpty()) {
            return ResponseEntity.notFound().build();
        }
        User user = userOpt.get();
        return ResponseEntity.ok(exerciseRecordRepository.findByUserOrderByStartTimeDesc(user));
    }
    
    /**
     * 获取指定用户的分页运动记录
     */
    @GetMapping("/user/{userId}/paged")
    public ResponseEntity<Page<ExerciseRecord>> getUserExerciseRecordsPaged(
            @PathVariable Long userId, Pageable pageable) {
        Optional<User> userOpt = userRepository.findById(userId);
        if (userOpt.isEmpty()) {
            return ResponseEntity.notFound().build();
        }
        User user = userOpt.get();
        return ResponseEntity.ok(exerciseRecordRepository.findByUserOrderByStartTimeDesc(user, pageable));
    }
    
    /**
     * 获取指定用户的运动记录（按日期范围）
     */
    @GetMapping("/user/{userId}/range")
    public ResponseEntity<List<ExerciseRecord>> getUserExerciseRecordsByDateRange(
            @PathVariable Long userId,
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date startDate,
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date endDate) {
        
        Optional<User> userOpt = userRepository.findById(userId);
        if (userOpt.isEmpty()) {
            return ResponseEntity.notFound().build();
        }
        User user = userOpt.get();
        
        List<ExerciseRecord> records = exerciseRecordRepository.findByUserAndStartTimeBetweenOrderByStartTimeDesc(
                user, startDate, endDate);
        return ResponseEntity.ok(records);
    }
    
    /**
     * 获取指定用户的健身统计数据
     */
    @GetMapping("/user/{userId}/stats")
    public ResponseEntity<?> getUserExerciseStats(@PathVariable Long userId) {
        Optional<User> userOpt = userRepository.findById(userId);
        if (userOpt.isEmpty()) {
            return ResponseEntity.notFound().build();
        }
        User user = userOpt.get();
        
        Integer totalDuration = exerciseRecordRepository.getTotalDurationByUser(user);
        Double totalCalories = exerciseRecordRepository.getTotalCaloriesByUser(user);
        
        return ResponseEntity.ok(new StatsResponse(
                totalDuration != null ? totalDuration : 0,
                totalCalories != null ? totalCalories : 0.0
        ));
    }
    
    /**
     * 管理员修改用户的运动记录
     */
    @PutMapping("/user/{userId}/{recordId}")
    public ResponseEntity<ExerciseRecord> updateUserExerciseRecord(
            @PathVariable Long userId,
            @PathVariable Long recordId,
            @RequestBody ExerciseRecord exerciseRecord) {
        
        Optional<User> userOpt = userRepository.findById(userId);
        if (userOpt.isEmpty()) {
            return ResponseEntity.notFound().build();
        }
        ExerciseRecord exerciseRecordById = exerciseRecordService.getExerciseRecordById(recordId);

        // 确保只能修改指定用户的记录
        if (!exerciseRecordById.getUser().getId().equals(userId)) {
            return ResponseEntity.badRequest().build();
        }
        
        // 保留原始用户信息
        User originalUser = exerciseRecordById.getUser();
        exerciseRecord.setId(recordId);
        exerciseRecord.setUser(originalUser);
        ExerciseRecord exerciseRecord1 = exerciseRecordRepository.save(exerciseRecord);
        return ResponseEntity.ok(exerciseRecord1);
    }
    
    /**
     * 管理员删除用户的运动记录
     */
    @DeleteMapping("/user/{userId}/{recordId}")
    public ResponseEntity<MessageResponse> deleteUserExerciseRecord(
            @PathVariable Long userId,
            @PathVariable Long recordId) {
        
        Optional<ExerciseRecord> recordOpt = exerciseRecordRepository.findById(recordId);
        if (recordOpt.isEmpty()) {
            return ResponseEntity.ok(new MessageResponse());
        }
        
        ExerciseRecord record = recordOpt.get();
        // 确保只能删除指定用户的记录
        if (!record.getUser().getId().equals(userId)) {
            return ResponseEntity.badRequest().body(new MessageResponse());
        }
        
        exerciseRecordRepository.delete(record);
        return ResponseEntity.ok(new MessageResponse());
    }
    
    // 内部响应类
    static class StatsResponse {
        private final Integer totalDuration;
        private final Double totalCalories;
        
        public StatsResponse(Integer totalDuration, Double totalCalories) {
            this.totalDuration = totalDuration;
            this.totalCalories = totalCalories;
        }
        
        public Integer getTotalDuration() {
            return totalDuration;
        }
        
        public Double getTotalCalories() {
            return totalCalories;
        }
    }
} 